# -*- mode: python; coding: utf-8 -*-

# Test DB interface

import unittest
import sys
import os

sys.path.append("$basedir")
from ht import DB, WordsDB


class WordsDBTest(unittest.TestCase):

    filename = "/tmp/words.db"

    def setUp(self):
        if os.path.exists(self.filename):
            os.remove(self.filename)

    def test_01_createDB(self):
        db = WordsDB(self.filename)


    def test_02_addRow(self):
        db = WordsDB(self.filename)
        row = {"session":1, "hanzi":"你好", "pinyin":"nĭhăo", "spanish":"hola"}

        # Insert correct
        db.addRow(row)

        # Insert can overwrite
        self.assertRaises(DB.AlreadyExists, db.addRow, row)
        db.addRow(row, replace=True)


    def test_03_getRowsByColumn(self):
        db = WordsDB(self.filename)
        row = {"session":1, "hanzi":"你好", "pinyin":"nĭhăo", "spanish":"hola"}
        db.addRow(row)

        # Get rows works
        got = db.getRowsByCol("session", 1)
        self.assertTrue(len(got) == 1)
        got = got[0]
        got.pop("id")
        self.assertEqual(got, row)

        # Get rows is idempotent
        got = db.getRowsByCol("session", 1)[0]
        got.pop("id")
        self.assertEqual(got, row)

        # If row is changed, getRows will return the new value
        row = {"session":1, "hanzi":"再见", "pinyin":"zàijiàn", "spanish":"adios"}
        db.addRow(row, "session='1'", replace=True)
        got = db.getRowsByCol("session", 1)[0]
        got.pop("id")
        self.assertEqual(got, row)

        # If row does not exist, it will return empty
        got = db.getRowsByCol("session", 2)
        self.assertEqual(got, [])

        # If there are many rows, all are returned
        row2 = {"session":2, "hanzi":"你好", "pinyin":"nĭhăo", "spanish":"hola"}
        db.addRow(row2)
        row3 = {"session":3, "hanzi":"你好", "pinyin":"nĭhăo", "spanish":"hola"}
        db.addRow(row3)

        got = db.getRowsByCol("spanish", "hola")
        self.assertTrue(len(got) == 2)
        got[0].pop("id")
        got[1].pop("id")
        got.remove(row2)
        got.remove(row3)
        self.assertEqual(got, [])


UnitTestCase(WordsDBTest)

